var util = require('../../utils/util.js');
const utils = require('../../components/utils/utils');

Page({
  data: {
    openAttr: false,
    selected: '',
    selectPrice: '',
    selectMarketPrice: '',
    selectPic: '',
    selectStock: '',
    selectedText: '',
    selectGoodsSn: '',
    goods: {},
    number: 1,
    minNumber: 1,
    commodityAttr: [],
    selectGroup: {}, // 选中的SKU
    includeGroup: [],
    keyValue: [],
    cartGoods: [],
    cartGoodsDisabled: [],
    checkedAllStatus: false,
    firstIndex: 0,
    cartIds: [], //购物车id
    cartTotal: {
      "goodsCount": 0,
      "goodsAmount": 0.00,
      "checkedGoodsCount": 0,
      "checkedGoodsAmount": 0.00
    },
    actions: [{
      name: '删除',
      color: '#fff',
      fontsize: 28,
      width: 64,
      background: '#F82400'
    }],
    isEdit: false,
    footprintList: []
  },
  onLoad: function (options) {
    wx.setStorageSync("navUrl", "/pages/cart/cart");
  },
  onShow: function () {
    // 页面显示
    this.getCartList();
  },
  // 下拉刷新
  onPullDownRefresh: function () {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    var that = this;
    this.getCartList();
    // 隐藏导航栏加载框
    wx.hideNavigationBarLoading();
    // 停止下拉动作
    wx.stopPullDownRefresh();
  },
  updateSku: function () {
    var that = this;
    var value = [];
    for (var i = 0; i < that.data.keyValue.length; i++) {
      if (that.data.keyValue[i].selectedValue && that.data.keyValue[i].attrValueStatus[that.data.keyValue[i].selectedIndex]) {
        value.push(that.data.keyValue[i].selectedValue);
      }
    }
    if (value.length < that.data.keyValue.length) {
      util.showMsg('请选择完整！');
    } else {
      if (!that.data.includeGroup[0]) {
        util.showMsg('商家暂未添加商品规格！');
        that.setData({
          openAttr: !that.data.openAttr
        });
        return;
      }
      //更新购物车
      util.request('cart/updateSku', {
        skuId: that.data.selectGroup.id,
        goodsId: that.data.goods.id,
        referrerUserId: that.data.referrerUserId,
        number: that.data.number,
        selectedText: that.data.selectedText
      }, "POST").then(function (res) {
        let _res = res;
        if (_res.code == 0) {
          that.getCartList();
          that.setData({
            openAttr: !that.data.openAttr
          });
        } else {
          util.showMsg(_res.msg);
        }
      });
    }
  },
  updateSkuShow: function (e) {
    var that = this;
    that.setData({
      goods: {},
      minNumber: 1,
      selectPrice: '',
      selectMarketPrice: '',
      selectPic: '',
      selectStock: '',
      selectGoodsSn: '',
      commodityAttr: [],
      includeGroup: that.data.commodityAttr,
      keyValue: []
    })

    let index = e.currentTarget.dataset.index;
    util.request('goods/detail', {
      goodsId: e.currentTarget.dataset.id
    }).then(function (res) {
      if (res.code === 0) {
        that.setData({
          goods: res.data.info,
          minNumber: res.data.info.minSell || 1,
          number: that.data.cartGoods[index].number,
          selectPrice: res.data.info.retailPrice,
          selectMarketPrice: res.data.info.marketPrice,
          selectPic: res.data.info.listPicUrl,
          selectStock: res.data.info.goodsNumber,
          selectGoodsSn: res.data.info.goodsSn,
          commodityAttr: res.data.info.goodsSkuEntityList,
          includeGroup: res.data.info.goodsSkuEntityList,
        })
        that.distachAttrValue(that.data.commodityAttr);
        // 只有一个属性组合的时候默认选中
        // console.log(this.data.keyValue);
        if (that.data.commodityAttr.length == 1) {
          let selectedText = '';
          for (var i = 0; i < that.data.commodityAttr[0].keyValue.length; i++) {
            that.data.keyValue[i].selectedValue = that.data.commodityAttr[0].keyValue[i].value;
            that.data.keyValue[i].selectedIndex = 0
            selectedText += that.data.keyValue[i].key + '：' + that.data.keyValue[i].selectedValue + '；'
          }
          that.setData({
            selectedText: selectedText,
            selectGroup: that.data.commodityAttr[0],
            keyValue: that.data.keyValue
          });
        }
        that.setSelect();
        if (that.data.openAttr == false) {
          //打开规格选择窗口
          that.setData({
            openAttr: !that.data.openAttr
          });
        }
      }
    });
  },
  changeNumber: function (event) {
    let itemIndex = event.detail.index;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = event.detail.value;
    cartItem.number = number;
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.goodsId, number, cartItem.id);
  },
  /* 获取数据 */
  distachAttrValue: function (commodityAttr) {
    /**
    将后台返回的数据组合成类似
    {
    key:'型号',
    keyValue:['1','2','3']
    }
    */
    // 把数据对象的数据（视图使用），写到局部内
    var keyValue = this.data.keyValue;
    // 遍历获取的数据
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].keyValue.length; j++) {
        var attrIndex = this.getAttrIndex(commodityAttr[i].keyValue[j].key, keyValue);
        // console.log('属性索引', attrIndex);
        // 如果还没有属性索引为-1，此时新增属性并设置属性值数组的第一个值；索引大于等于0，表示已存在的属性名的位置
        if (attrIndex >= 0) {
          // 如果属性值数组中没有该值，push新值；否则不处理
          if (!this.isValueExist(commodityAttr[i].keyValue[j].value, keyValue[attrIndex].attrValues)) {
            keyValue[attrIndex].attrValues.push(commodityAttr[i].keyValue[j].value);
          }
        } else {
          keyValue.push({
            key: commodityAttr[i].keyValue[j].key,
            attrValues: [commodityAttr[i].keyValue[j].value]
          });
        }
      }
    }
    // console.log('result', keyValue)
    for (var i = 0; i < keyValue.length; i++) {
      for (var j = 0; j < keyValue[i].attrValues.length; j++) {
        if (keyValue[i].attrValueStatus) {
          keyValue[i].attrValueStatus[j] = true;
        } else {
          keyValue[i].attrValueStatus = [];
          keyValue[i].attrValueStatus[j] = true;
        }
      }
    }
    this.setData({
      keyValue: keyValue
    });
  },
  getAttrIndex: function (attrName, keyValue) {
    // 判断数组中的attrKey是否有该属性值
    for (var i = 0; i < keyValue.length; i++) {
      if (attrName == keyValue[i].key) {
        break;
      }
    }
    return i < keyValue.length ? i : -1;
  },
  isValueExist: function (value, valueArr) {
    // 判断是否已有属性值
    for (var i = 0; i < valueArr.length; i++) {
      if (valueArr[i] == value) {
        break;
      }
    }
    return i < valueArr.length;
  },
  /* 选择属性值事件 */
  selectAttrValue: function (e) {
    /*
    点选属性值，联动判断其他属性值是否可选
    {
    key:'型号',
    keyValue:['1','2','3'],
    selectedValue:'1',
    attrValueStatus:[true,true,true]
    }
    console.log(e.currentTarget.dataset);
    */
    var keyValue = this.data.keyValue;
    var index = e.currentTarget.dataset.index; //属性索引
    var key = e.currentTarget.dataset.key;
    var value = e.currentTarget.dataset.value;
    var valueindex = e.currentTarget.dataset.vi;
    if (e.currentTarget.dataset.status || index == this.data.firstIndex) {
      if (e.currentTarget.dataset.selectedvalue == e.currentTarget.dataset.value) {
        // 取消选中
        this.disSelectValue(keyValue, index, key, value, valueindex);
      } else {
        // 选中
        this.selectValue(keyValue, index, key, value, valueindex);
      }
    }
  },
  /* 选中 */
  selectValue: function (keyValue, index, key, value, valueindex) {
    var includeGroup = [];
    keyValue[index].selectedValue = value;
    keyValue[index].selectedIndex = valueindex;

    var commodityAttr = this.data.includeGroup;
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].keyValue.length; j++) {
        if (commodityAttr[i].keyValue[j].key == key && commodityAttr[i].keyValue[j].value == value) {
          includeGroup.push(commodityAttr[i]);
        }
      }
    }

    // 判断属性是否可选
    for (var i = 0; i < keyValue.length; i++) {
      for (var j = 0; j < keyValue[i].attrValues.length; j++) {
        keyValue[i].attrValueStatus[j] = false;
      }
    }
    for (var i = 0; i < includeGroup.length; i++) {
      var flag = includeGroup[i].keyValue.every(function (ikv, ikvIndex) {
        if (keyValue[ikvIndex].key === ikv.key) {
          return keyValue[ikvIndex].selectedValue === ikv.value
        }
        return true;
      })
      // 所有key-value对都命中
      if (flag) {
        this.setData({
          selectGroup: includeGroup[i]
        });
      }
      for (var k = 0; k < keyValue.length; k++) {
        for (var j = 0; j < includeGroup[i].keyValue.length; j++) {
          if (keyValue[k].key == includeGroup[i].keyValue[j].key) {
            for (var m = 0; m < keyValue[k].attrValues.length; m++) {
              if (keyValue[k].attrValues[m] == includeGroup[i].keyValue[j].value || (includeGroup[i].keyValue[j].key == key && includeGroup[i].keyValue[j].value == value)) {
                keyValue[k].attrValueStatus[m] = true;
              }
            }
          }
        }
      }
    }
    this.setData({
      keyValue: keyValue
    });

    var count = 0;
    for (var i = 0; i < keyValue.length; i++) {
      for (var j = 0; j < keyValue[i].attrValues.length; j++) {
        if (keyValue[i].selectedValue) {
          count++;
          break;
        }
      }
    }
    if (count < 2) { // 第一次选中，同属性的值都可选
      this.setData({
        firstIndex: index
      });
    } else {
      this.setData({
        firstIndex: -1
      });
    }
    this.setSelect();
  },
  /* 取消选中 */
  disSelectValue: function (keyValue, index, key, value, valueindex) {
    var that = this;
    var commodityAttr = that.data.commodityAttr;
    keyValue[index].selectedValue = '';
    keyValue[index].selectedIndex = '';

    // 判断属性是否可选
    for (var i = 0; i < keyValue.length; i++) {
      for (var j = 0; j < keyValue[i].attrValues.length; j++) {
        keyValue[i].attrValueStatus[j] = true;
      }
    }
    that.setData({
      includeGroup: commodityAttr,
      keyValue: keyValue,
      selectGroup: {}
    });

    for (var i = 0; i < keyValue.length; i++) {
      if (keyValue[i].selectedValue) {
        that.selectValue(keyValue, i, keyValue[i].key, keyValue[i].selectedValue, valueindex);
      }
    }
    that.setSelect();
  },
  setSelect: function () {
    var that = this;
    var valueStr = "";
    var value = [];
    var selectedText = '';
    for (var i = 0; i < that.data.keyValue.length; i++) {
      if (that.data.keyValue[i].selectedValue && that.data.keyValue[i].attrValueStatus[that.data.keyValue[i].selectedIndex]) {
        value.push(that.data.keyValue[i].selectedValue);
        selectedText += that.data.keyValue[i].key + '：' + that.data.keyValue[i].selectedValue + '；'
      }
    }
    for (var i = 0; i < value.length; i++) {
      valueStr += value[i] + ",";
    }
    valueStr = valueStr.substr(0, valueStr.length - 1)
    that.setData({
      selected: valueStr
    })
    if (!that.data.selectGroup.id) {
      that.setData({
        selectPrice: that.data.goods.retailPrice,
        selectStock: that.data.goods.goodsNumber,
        selectPic: that.data.goods.listPicUrl,
        selectGoodsSn: that.data.goods.goodsSn,
        selectMarketPrice: that.data.goods.marketPrice,
        selectedText: selectedText
      })
      return;
    }
    that.setData({
      selectPrice: that.data.selectGroup.retailPrice,
      selectStock: that.data.selectGroup.goodsNumber,
      selectPic: that.data.selectGroup.listPicUrl,
      selectMarketPrice: that.data.selectGroup.marketPrice,
      selectGoodsSn: that.data.selectGroup.goodsSn,
      selectedText: selectedText
    })
  },
  previewSkuImg(e) {
    wx.previewImage({
      urls: [e.currentTarget.dataset.url], // 需要预览的图片http链接列表
    })
  },

  switchAttrPop: function () {
    let that = this;
    if (that.data.openAttr == false) {
      that.setData({
        openAttr: !that.data.openAttr
      });
    } else {
      that.setData({
        openAttr: !that.data.openAttr,
      })
    }
  },
  toIndexPage: function () {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },
  getCartList: function () {
    let that = this;
    util.request('cart/myCart', {}).then(function (res) {
      if (res.code === 0) {
        that.setData({
          cartGoods: res.able,
          cartGoodsDisabled: res.disabled,
          cartTotal: res.cartTotal
        });
      }

      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });

      that.getFootprintList();
    });
  },
  isCheckedAll: function () {
    //判断购物车商品已全选
    return this.data.cartGoods.every(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  getFootprintList() {
    let that = this;
    util.request('user/footprintList').then(function (res) {
      if (res.code === 0) {
        if (res.data.records) {
          that.setData({
            footprintList: res.data.records
          });
        }
      }
    });
  },
  changeNum: function (event) {
    let that = this;
    let index = event.detail.index;
    let number = event.detail.value;
    let cartItem = that.data.cartGoods[index]
    cartItem.number = number;
    that.updateCart(cartItem.goodsId, number, cartItem.id);
  },
  updateCart: function (goodsId, number, id) {
    let that = this;

    util.request('cart/update', {
      goodsId: goodsId,
      number: number,
      id: id
    }, 'POST').then(function (res) {
      if (res.code === 0) {
        that.setData({
          cartGoods: res.able,
          cartGoodsDisabled: res.disabled,
          cartTotal: res.cartTotal
        });
      }

      that.setData({
        number: number,
        openAttr: false,
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },
  clearDisable: function () {
    //获取已选择的商品
    let cartIds = [];
    this.data.cartGoodsDisabled.forEach((item) => {
      cartIds.push(item.id)
    })
    this.cartDelete(cartIds.join(','))
  },
  editGoods: function () {
    this.setData({
      isEdit: !this.data.isEdit
    })
  },
  navToGoodsDetail: function (event) {
    let goodsId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/goods/goods?id=' + goodsId,
    })
  },
  checkedAll: function () {
    let that = this;

    var cartIds = this.data.cartGoods.map(function (v) {
      return v.id;
    });
    util.request('cart/checked', {
      cartIds: cartIds,
      isChecked: that.isCheckedAll() ? 0 : 1
    }, 'POST').then(function (res) {
      if (res.code === 0) {
        that.setData({
          cartGoods: res.able,
          cartGoodsDisabled: res.disabled,
          cartTotal: res.cartTotal
        });
      }

      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },
  deleteCart: function () {
    //获取已选择的商品
    let that = this;

    let cartSelectGoods = this.data.cartGoods.filter(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });

    if (cartSelectGoods.length <= 0) {
      return false;
    }

    let cartIds = cartSelectGoods.map(function (element, index, array) {
      if (element.checked == true) {
        return element.id;
      }
    });
    that.cartDelete(cartIds.join(','))
  },
  cartDelete(cartIds) {
    let that = this;
    wx.showModal({
      title: '',
      content: '确定要删除选中的商品？',
      success: function (res) {
        if (res.confirm) {
          util.request('cart/delete', {
            cartIds: cartIds
          }, 'POST').then(function (res) {
            if (res.code === 0) {
              that.setData({
                cartGoods: res.able,
                cartGoodsDisabled: res.disabled,
                cartTotal: res.cartTotal
              });
            }
            that.setData({
              checkedAllStatus: that.isCheckedAll()
            });
          });
        }
      }
    })
  },
  checkedItem: function (event) {
    let itemIndex = event.currentTarget.dataset.index;
    let that = this;

    util.request('cart/checked', {
      id: that.data.cartGoods[itemIndex].id,
      isChecked: that.data.cartGoods[itemIndex].checked ? 0 : 1
    }, 'POST').then(function (res) {
      if (res.code === 0) {
        that.setData({
          cartGoods: res.able,
          cartGoodsDisabled: res.disabled,
          cartTotal: res.cartTotal
        });
      }

      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });

  },

  checkoutOrder: function () {
    //获取已选择的商品
    let that = this;

    var checkedGoods = that.data.cartGoods.filter(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });

    if (checkedGoods.length <= 0) {
      util.showMsg('您还没有选择商品哦');
      return false;
    }

    wx.navigateTo({
      url: '../shopping/checkout/checkout'
    })
  }
})
